import { httpPost } from './http.js';

(() => {
  const oApp = document.querySelector('#app');
  const oList = oApp.querySelector('#list');
  const oAddBtn = oApp.querySelector('.add-btn');
  const oTodoTitle = oApp.querySelector('.todo-title');
  const oTodoContent = oApp.querySelector('.todo-content');

  const init = () => {
    bindEvent();
  };

  function handleListClick(e) {
    const tar = e.target;
    const className = tar.className;
    switch (className) {
      case 'toggle-check-box':
        handleCheckBoxClick(tar);
        break;
      case 'remove-btn':
        handleRemoveBtnClick(tar);
        break;
      default:
        break;
    }
  }

  function handleAddBtnClick(e) {
    //获取输入框文本信息
    const title = oTodoTitle.value;
    const content = oTodoContent.value;
    if (!title.length || !content.length) {
      return;
    }
    addTodo({ title, content }).then((res) => {
      //请求成功并响应成功状态码
      if (res.code === 0) {
        const data = res.data;
        const listItem = createItem(data);
        oList.appendChild(listItem);
      }
    });
    oTodoTitle.value = '';
    oTodoContent.value = '';
  }

  function handleCheckBoxClick(tar) {
    const id = tar.dataset.id;
    toggleTodo(id).then((res) => {
      if (res.code === 0) {
        const oTitle = tar.parentNode.querySelector('a');
        oTitle.classList.toggle('completed');
      }
    });
  }

  function handleRemoveBtnClick(tar) {
    const id = tar.dataset.id;
    removeTodo(id).then((res) => {
      if (res.code === 0) {
        tar.parentNode.remove();
      }
    });
  }

  function createItem(item) {
    const oLi = document.createElement('li');
    oLi.innerHTML = `
      <li>
        <input 
          type="checkbox" 
          ${item.completed ? 'checked' : ''} 
          data-id="${item._id}"
          class="toggle-check-box"
        />
        <a 
          href="http://localhost:8000/detail/${item._id}"
          class="${item.completed ? 'completed' : ''}"
        >${item.title}</a>
        <button 
          data-id="${item._id}"
          class="remove-btn"
        >Remove</button>
    </li>
    `;
    return oLi;
  }

  async function addTodo(todo) {
    return await httpPost('/add_todo', todo);
  }

  async function toggleTodo(id) {
    return await httpPost('/toggle_todo', { id });
  }

  async function removeTodo(id) {
    return await httpPost('/remove_todo', { id });
  }

  function bindEvent() {
    oAddBtn.addEventListener('click', handleAddBtnClick, false);
    oList.addEventListener('click', handleListClick, false);
  }

  init();
})();
